import Vue from 'vue'
import Vuex from 'vuex'
import api from "@/api/api"
import MinCache from'@/common/util/MinCache.js'
import { ACCESS_TOKEN,USER_NAME,USER_INFO,X_TENANT_ID } from "@/common/util/constants"

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    token: '',
    memberId:'',
    username: '',
    sex: '',
    age: '',
    avatar: '',
	phone: ''
  },
  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_NAME: (state, { username }) => {
      state.username = username
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar
    },
    SET_MEMBERID: (state, memberId) => {
      state.memberId = memberId
    },
	SET_PHONE: (state, phone) => {
	  state.phone = phone
	},
	SET_SEX: (state, sex) => {
	  state.sex = sex
	}
  },
  actions: {
    // 登录
    mLogin({ commit }, memberInfo) {
      return new Promise((resolve, reject) => {
       api.login(memberInfo).then(response => {
          if(response.data.code ==200){ 
            const result = response.data.data
            const memberInfo = result.memberInfo
			uni.setStorageSync(ACCESS_TOKEN,result.token);
			uni.setStorageSync(USER_INFO,memberInfo);
            commit('SET_TOKEN', result.token)
            commit('SET_AVATAR', memberInfo.avatar)
            commit('SET_NAME', { username: memberInfo.username})
			commit('SET_MEMBERID', memberInfo.memberId)
			commit('SET_SEX', memberInfo.sex) 
			commit('SET_PHONE', memberInfo.phone)
            resolve(response)
          }else{
            resolve(response)
          }
        }).catch(error => {
			console.log("catch===>response",response)
          reject(error)
        })
      })
    },
    // 登出
    Logout({ commit, state }) {
      return new Promise((resolve) => {
        let logoutToken = state.token;
        commit('SET_TOKEN', '')
        uni.removeStorageSync(ACCESS_TOKEN)
        api.logout(logoutToken).then(() => {
          resolve()
        }).catch(() => {
          resolve()
        })
      })
    },

  },
  getters:{
    token: state => state.token,
	username: state => {state.username=uni.getStorageSync(USER_INFO).username; return state.username},
	memberId: state => {state.memberId=uni.getStorageSync(USER_INFO).memberId; return state.memberId},
	avatar: state => {state.avatar=uni.getStorageSync(USER_INFO).avatar; return state.avatar},
	phone: state => {state.phone=uni.getStorageSync(USER_INFO).phone; return state.phone},
	sex: state => {state.sex=uni.getStorageSync(USER_INFO).sex; return state.sex},
	
  }
})
